const schedule = require('node-schedule');
// 添加日志工具（中国标准时间UTC+8）
const logger = (message) => {
    const now = new Date();
    const chinaTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
    const chinaTimeStr = chinaTime.toISOString().replace('Z', '+08:00');
    console.log(`[${chinaTimeStr}] ${message}`);
};
const db = require('./utils/db');
const { generatePassword, encrypt } = require('./utils/crypto');
const { changePassword } = require('./utils/ssh');
const serverManager = require('./utils/serverManager');

async function resetExpiredPasswords() {
    logger('开始检查过期密码...');
    const now = new Date();

    // 获取所有已过期但未重置的请求
    logger('查询过期请求...');
    const [expiredRequests] = await db.query(
        `SELECT r.*, a.target_host 
     FROM requests r
     JOIN allowed_accounts a ON r.account_name = a.account_name
     WHERE r.expire_time < ? AND r.temp_pwd IS NOT NULL`,
        [now]
    );

    logger(`找到 ${expiredRequests.length} 个过期请求需要处理`);
    for (const request of expiredRequests) {
        try {
            // 生成新密码
            logger(`为账号 ${request.account_name} 生成新密码...`);
            const newPassword = generatePassword();
            const encryptedPassword = await encrypt(newPassword);

            // 更新服务器密码
            logger(`更新账号 ${request.account_name} 的密码，主机: ${request.target_host}`);
            await changePassword(
                request.account_name,
                newPassword,
                request.account_name,
                request.target_host
            );

            // 只有当密码修改成功时才更新数据库记录
            // 清除临时密码标记
            logger(`清除请求 ${request.id} 的临时密码标记`);
            await db.query(
                `UPDATE requests SET temp_pwd = NULL WHERE id = ?`,
                [request.id]
            );
            logger(`写入新密码`);
            await db.query(
                `UPDATE credentials SET encrypted_pwd = ? WHERE username = ? and c_host = ?`,
                [encryptedPassword,request.account_name,request.target_host]
            );

            logger(`已重置账号 ${request.account_name} 的密码`);
        } catch (error) {
            logger(`重置密码失败: ${request.account_name}, 错误: ${error.message}`);
        }
    }
}

function start() {
    logger('配置定时任务...');
    // 每5分钟检查一次过期密码
    schedule.scheduleJob('*/5 * * * *', resetExpiredPasswords);
    logger('定时任务已启动，每5分钟检查一次过期密码');
}

module.exports = { start };